package com.itheima.tanhua.dubbo.mongo.api.impl;

import com.itheima.tanhua.api.FriendApi;
import com.itheima.tanhua.mongo.Friend;
import com.itheima.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author Lff
 * @date 2022/3/31
 */
@DubboService
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongo;

    /**
     * 绑定好友关系
     *
     * @param userId
     * @param friendId
     */
    @Override
    public void saveFriendRelation(Long userId, Long friendId) {
        Friend friend = new Friend();
        friend.setFriendId(friendId);
        friend.setUserId(userId);
        long time = System.currentTimeMillis();
        friend.setCreated(time);
        Query q1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if (!mongo.exists(q1, Friend.class)) {
            mongo.save(friend);
        }
        Friend friend2 = new Friend();
        friend2.setFriendId(userId);
        friend2.setUserId(friendId);
        friend2.setCreated(time);
        Query q2 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if (!mongo.exists(q2, Friend.class)) {
            //身份互换
            mongo.save(friend2);
        }
    }

    /**
     * 获取联系人列表
     *
     * @param id
     * @param page
     * @param pagesize
     * @param
     * @return
     */
    @Override
    public PageResult getUserFriendsById(Long id, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(id);
        Query created = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Friend> friends = mongo.find(created, Friend.class);
        PageResult pr = new PageResult(page, pagesize, 0l, friends);
        return pr;
    }

    /**
     * 移除好友关系
     *
     * @param userId
     * @param friendId
     */
    @Override
    public void deleteFriendRelation(Long userId, Long friendId) {
        Query q1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if (!mongo.exists(q1, Friend.class)) {
            mongo.remove(q1, Friend.class);
        }
        Query q2 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if (!mongo.exists(q2, Friend.class)) {
            //身份互换
            mongo.remove(q2, Friend.class);
        }
    }
}
